package com.hjm.java.service;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.hjm.java.sql.HJMHelper;
import com.hjm.java.utils.HjmFailCallBack;
import com.hjm.java.utils.HjmGlideUtil;
import com.hjm.java.utils.HjmListCallBack;
import com.hjm.java.utils.HjmObjectCallBack;
import com.hjm.java.utils.HjmSuccessCallBack;
import com.hjm.java.entity.Order;
import com.hjm.java.utils.HjmSuccessObjectCallBack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderService extends BaseService {
    private static final String TAG = "OrderService";
    private List<Order> orderList;
    public List<com.hjm.ui.order.entity.Order> noPayOrderList, noTxOrderList, noRxOrderList, doneOrderList;

    public OrderService(Context mContext, Handler mHandler) {
        super(mContext, mHandler);
    }

    public void createOrder(Order order, HjmSuccessObjectCallBack<String> successObjectCallBack, HjmFailCallBack onFailCallBack) {
        httpUtils.postByToken(baseUrl + "/order", order, String.class, (HjmObjectCallBack<String>) (isSuccess, string, msg) -> {
            mHandler.post(() -> {
                if (isSuccess)
                    successObjectCallBack.onSuccess(string);
                else
                    onFailCallBack.onFail(msg);
            });
        });
    }

    public void createOrder(int[] orderIds, HjmSuccessCallBack successCallBack, HjmFailCallBack failCallBack) {
        httpUtils.postByToken(baseUrl + "/order/co", orderIds, Order.class, (HjmListCallBack<Order>) (isSuccess, orders, msg) -> {
            if (isSuccess) {
                HjmGlideUtil.UrlToBitmap(mContext, baseImgUrl,
                        orders.stream().map(Order -> String.valueOf(Order.getGoodsIconId())).toArray(String[]::new),
                        HJMHelper.getInstance(mContext),
                        (position, bitmap) -> {
                            Log.d(TAG, "createOrder: 获得图片，位置：" + position+"，宽度："+bitmap.getWidth()+" 高度："+bitmap.getHeight());
                            orders.get(position).setGoodsIcon(bitmap);
                        },
                        () -> {
                            mHandler.post(() -> {
                                this.orderList = orders;
                                successCallBack.onSuccess();
                            });
                        });
            } else {
                failCallBack.onFail(msg);
            }
        });
    }

    /**
     * 获取分类的订单列表
     *
     * @param callBack 回调Map
     */
    public void getOrderList(HjmObjectCallBack<Map<String, List<com.hjm.ui.order.entity.Order>>> callBack) {
        noPayOrderList = new ArrayList<>();
        noTxOrderList = new ArrayList<>();
        noRxOrderList = new ArrayList<>();
        doneOrderList = new ArrayList<>();
        httpUtils.getListByToken(baseUrl + "/order/list", Order.class, (isSuccess, orderList, msg) -> {
            if (isSuccess) {
                HjmGlideUtil.UrlToBitmap(mContext, baseImgUrl,
                        orderList.stream().map(Order -> String.valueOf(Order.getGoodsIconId())).toArray(String[]::new),
                        HJMHelper.getInstance(mContext),
                        (position, bitmap) -> {
                            orderList.get(position).setGoodsIcon(bitmap);
                        },
                        () -> {
                            mHandler.post(() -> {
                                callBack.call(true, orderListToMap(orderList), null);
                            });
                        });
            } else {
                callBack.call(false, new HashMap<>(), msg);
            }
        });
    }

    /**
     * 更新订单状态
     *
     * @param orderId
     * @param state
     * @param successCallBack
     * @param failCallBack
     */
    public void updateOrderState(int orderId, String state, HjmSuccessCallBack successCallBack, HjmFailCallBack failCallBack) {
        //构建请求体
        String requestBody = "{\"id\":" + orderId + ",\"state\":" + state + "}";
        httpUtils.putByToken(baseUrl + "/order", JSONObject.parseObject(requestBody), String.class, (isSuccess, string, msg) -> {
            mHandler.post(() -> {
                if (isSuccess) {
                    successCallBack.onSuccess();
                } else {
                    failCallBack.onFail(msg);
                }
            });
        });
    }

    public void deleteOrder(int orderId, HjmSuccessCallBack successCallBack, HjmFailCallBack failCallBack) {
        httpUtils.deleteByToken(baseUrl + "/order/?id=" + orderId, String.class, (isSuccess, string, msg) -> {
            mHandler.post(() -> {
                if (isSuccess) {
                    successCallBack.onSuccess();
                } else {
                    failCallBack.onFail(msg);
                }
            });
        });
    }

    /**
     * 按照订单状态分类
     *
     * @param orderList
     * @return
     */
    Map<String, List<com.hjm.ui.order.entity.Order>> orderListToMap(List<Order> orderList) {
        for (Order order : orderList) {
            switch (order.getState()) {
                case 2:
                    noPayOrderList.add(order);
                    break;
                case 3:
                    noTxOrderList.add(order);
                    break;
                case 4:
                    noRxOrderList.add(order);
                    break;
                case 5:
                    doneOrderList.add(order);
                    break;
            }
        }
        Log.d(TAG, "getOrderList: 订单获取成功，其中\n未支付订单数量为" + noPayOrderList.size() + "\n未发货订单数量为" + noTxOrderList.size() + "\n未收货订单数量为" + noRxOrderList.size() + "\n已完成订单数量为" + doneOrderList.size());
        Map<String, List<com.hjm.ui.order.entity.Order>> result = new HashMap<>();
        result.put("2", noPayOrderList);
        result.put("3", noTxOrderList);
        result.put("4", noRxOrderList);
        result.put("5", doneOrderList);
        return result;
    }

    public List<com.hjm.ui.order.entity.Order> getOrderList() {
        List<com.hjm.ui.order.entity.Order> orders = new ArrayList<>();
        com.hjm.ui.order.entity.Order order = new com.hjm.ui.order.entity.Order();
        for (Order orderSource : orderList) {
            order.setGoodsType(orderSource.getGoodsType());
            order.setGoodsId(orderSource.getGoodsId());
            order.setGoodsName(orderSource.getGoodsName());
            order.setOrderId(orderSource.getOrderId());
//            order.setGoodsIcon(orderSource.getGoodsIcon());
            order.setPrice(orderSource.getPrice());
            order.setGoodsNum(orderSource.getGoodsNum());
            order.setGoodsIconId(orderSource.getGoodsIconId());
            order.setGoodsIcon(orderSource.getGoodsIcon());
//            ClassCopyUtil.copyProperties(orderSource, order);
            orders.add(order);
        }
        return orders;
    }
}
